package com.cc.AOP;

import com.cc.mapper.EmologinMapper;

import com.cc.pojo.Emp;
import com.cc.pojo.EmpLoginLog;
import com.cc.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Slf4j
@Aspect
@Component
public class LoginAspect {
    @Autowired
    private EmologinMapper emploginMapper;

    @Around( "execution(* com.cc.controller.LoginController.login(..))")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        log.info("LoginAspect.around()");
        EmpLoginLog empLogin = new EmpLoginLog();
        empLogin.setLoginTime(LocalDateTime.now());
        Object result= null;
        try {
            setLoginInfo(empLogin, joinPoint);
            result = joinPoint.proceed();
            setJwt(empLogin, result);
        } catch (Throwable e) {
            empLogin.setIsSuccess((short)0);
        } finally {
            empLogin.setCostTime(System.currentTimeMillis()-start);
            emploginMapper.insert(empLogin);
        }
        log.info("LoginAspect.around()");
        return result;
    }

    private void setJwt(EmpLoginLog empLogin, Object result) {
        if(result instanceof Result){
            Result result1=(Result)result;
            if (result1.getCode()==1){
                empLogin.setIsSuccess((short)1);
                empLogin.setJwt(result1.getData().toString());

            }else {
                empLogin.setIsSuccess((short)0);
            }

        }

    }

    private void setLoginInfo(EmpLoginLog empLogin, ProceedingJoinPoint joinPoint) {

        Object args=joinPoint.getArgs()[0];
        Emp emp=( Emp)args;

        empLogin.setUsername(emp.getUsername());
        empLogin.setPassword(emp.getPassword());

    }
}
